package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.common.util.UserUtil;
import com.egu.mapper.EmailInfoMapper;
import com.egu.model.EmailInfo;
import com.egu.model.EmailInfoExample;
import com.egu.model.EmailInfoExample.Criteria;
import com.egu.model.User;
import com.egu.service.EmailInfoService;
import com.egu.vo.EmailInfoVo;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;

@Service
public class EmailInfoServiceImpl implements EmailInfoService {

	
	@Autowired
	private EmailInfoMapper emailInfoMapper;
	@Override
	public RequestPageVo<EmailInfoVo> getVoList(PageParam param, EmailInfoVo emailInfoVo) {
		User currentUser = UserUtil.getCurrentUser();
		RequestPageVo<EmailInfoVo> result = new RequestPageVo<EmailInfoVo>();
		EmailInfoExample example = new EmailInfoExample();
        Criteria criteria = example.createCriteria();
        criteria.andIsUsedEqualTo("1");
        criteria.andEmailStateEqualTo(emailInfoVo.getEmailState());
        
        criteria.andUserIdEqualTo(currentUser.getId());
        /*if(currentUser.getRolePower()==1) {
        	criteria.andUserIdEqualTo(currentUser.getId());
    	}*/
        
        if (StringUtils.isNotBlank(emailInfoVo.getEmailTheme())) {
			criteria.andEmailThemeLike("%"+emailInfoVo.getEmailTheme()+"%");
		}
        int countByExample = emailInfoMapper.countByExample(example);
        if(countByExample>0) {
        	example.setStartPage(param.getOffset());
        	example.setPageSize(param.getLimit());
        	//f      u      c       k
        	emailInfoVo.setIsUsed("1");
        	
        	/*if(currentUser.getRolePower()==1) {
        		emailInfoVo.setUserId(currentUser.getId());
        	}*/
        	
        	emailInfoVo.setUserId(currentUser.getId());
        	criteria.andEmailStateEqualTo(emailInfoVo.getEmailState());
        	List<EmailInfoVo> list = emailInfoMapper.selectByEmailInfoVo(emailInfoVo);
        	result.setTotal(countByExample);
        	result.setRows(list);
        }
		return result;
	}

	@Override
	@Transactional
	public RequestResultVo<EmailInfo> saveOrUpdate(EmailInfo emailInfo) {
		emailInfo.setUserId(UserUtil.getCurrentUser().getId());
		if (emailInfo.getId() == null) {
			emailInfoMapper.insertSelective(emailInfo);
		} else {
			emailInfoMapper.updateByPrimaryKeySelective(emailInfo);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<EmailInfo> deleteDataById(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public EmailInfoVo getDataById(Integer id) {
		List<EmailInfoVo> list=emailInfoMapper.getDateById(id);
		if(list.size()>0) {
			EmailInfoVo emailInfoVo = list.get(0);
			return emailInfoVo;
		}
		return null;
	}

}
